﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    /// <summary>
    /// 执行确认单
    /// </summary>
    public class sli_work_noticeController : ApiController
    {
        // GET api/<controller>
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetTableBysale_order_view1(int page = 1, int pageSize = 10, string Fcustname = null,string FBillNo=null,string Fnote = null)
        {
            var context = new YourDbContext();
            IQueryable<sli_work_notice> query = context.Sli_work_notice;

            if (!string.IsNullOrEmpty(Fcustname))
            {
                query = query.Where(q => q.Fcustname.Contains(Fcustname));
            }
            if (!string.IsNullOrEmpty(FBillNo))
            {
                query = query.Where(q => q.Fbillno.Contains(FBillNo));
            }
            if (!string.IsNullOrEmpty(Fcustname))
            {
                query = query.Where(q => q.Fnote.Contains(Fnote));
            }

            //if (fid.HasValue)
            //{
            //    query = query.Where(t => t.fid == fid.Value);
            //}

            var totalCount = query.Count(); //记录数
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 页数
            var paginatedQuery = query.OrderBy(b => b.Fbillno).Skip((page - 1) * pageSize).Take(pageSize); //  某页记录
            //var datas = query.ToList();
            var result = paginatedQuery.Select(a => new
            {
                a.Id,
                a.Fcustname,
                a.Fbillno,
                a.Forderno,
                a.Fnotes,
                a.Fdate,
                a.Fqty,
                a.Fweight,
                a.Fsumweight,
                a.Fplanstart,
                a.Fplanend,
                a.Fordertype,
                a.Fforgeqty,
                a.Fforgeweight,
                a.Fname,
                a.Fslimetal,
                a.Fdescription,
                a.Fslidrawingno,
                a.Fsliheattreatment,
                a.Fsliexplanation,
                a.FsliTestBarQty,
                a.Fnote
            });
            var response = new    // 定义 前端返回数据  总记录，总页，当前页 ，size,返回记录
            {
                code = 200,
                msg = "OK",
                data = new
                {
                    totalCounts = totalCount,
                    totalPagess = totalPages,
                    currentPages = page,
                    pageSizes = pageSize,
                    data = paginatedQuery
                }
            };

            return Json(response);
        }


        [HttpGet]
        [Route("api/sli_work_notice/ExportToExcel")]
        public HttpResponseMessage ExportToExcel(string Fcustname = null, string FBillNo = null, string Fnote = null)
        {
            try
            {
                using (var context = new YourDbContext())
                {
                    // 构建基础查询
                    IQueryable<sli_work_notice> query = context.Sli_work_notice;

                    // 应用过滤条件
                    if (!string.IsNullOrEmpty(Fcustname))
                        query = query.Where(q => q.Fcustname.Contains(Fcustname));
                    if (!string.IsNullOrEmpty(FBillNo))
                        query = query.Where(q => q.Fbillno.Contains(FBillNo));
                    if (!string.IsNullOrEmpty(Fnote))
                        query = query.Where(q => q.Fnote.Contains(Fnote));

                    var data = query.OrderByDescending(b => b.Id).ToList();

                    // 创建Excel文档
                    var workbook = new XSSFWorkbook();
                    var sheet = workbook.CreateSheet("工单数据");

                    // 创建表头样式
                    var headerStyle = workbook.CreateCellStyle();
                    var headerFont = workbook.CreateFont();
                    headerFont.IsBold = true;
                    headerStyle.SetFont(headerFont);
                    headerStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
                    headerStyle.FillPattern = FillPattern.SolidForeground;

                    // 创建表头
                    var headerRow = sheet.CreateRow(0);
                    var headers = new[]
                    {
                "客户名称", "单据编号", "订单号", "日期", "数量",
                "重量","总量", "计划开始", "计划结束", "订单类型", "锻件数量",
                "锻件重量", "名称", "钢锭材质", "描述", "图纸编号",
                "热处理", "说明", "试棒数量", "备注"
            };

                    for (int i = 0; i < headers.Length; i++)
                    {
                        var cell = headerRow.CreateCell(i);
                        cell.SetCellValue(headers[i]);
                        cell.CellStyle = headerStyle;
                    }

                    // 填充数据
                    int rowNum = 1;
                    foreach (var item in data)
                    {
                        var row = sheet.CreateRow(rowNum++);
                        row.CreateCell(0).SetCellValue(item.Fcustname);
                        row.CreateCell(1).SetCellValue(item.Fbillno);
                        row.CreateCell(2).SetCellValue(item.Forderno);
                        row.CreateCell(3).SetCellValue(item.Fdate?.ToString("yyyy-MM-dd"));
                        row.CreateCell(4).SetCellValue((double)item.Fqty.GetValueOrDefault());
                        row.CreateCell(5).SetCellValue((double)item.Fweight.GetValueOrDefault());
                        row.CreateCell(6).SetCellValue((double)item.Fsumweight.GetValueOrDefault());
                        row.CreateCell(7).SetCellValue(item.Fplanstart?.ToString("yyyy-MM-dd"));
                        row.CreateCell(8).SetCellValue(item.Fplanend?.ToString("yyyy-MM-dd"));
                        row.CreateCell(9).SetCellValue(item.Fordertype);
                        row.CreateCell(10).SetCellValue(item.Fforgeqty.GetValueOrDefault());
                        row.CreateCell(11).SetCellValue((double)item.Fforgeweight.GetValueOrDefault());
                        row.CreateCell(12).SetCellValue(item.Fname);
                        row.CreateCell(13).SetCellValue(item.Fslimetal);
                        row.CreateCell(14).SetCellValue(item.Fdescription);
                        row.CreateCell(15).SetCellValue(item.Fslidrawingno);
                        row.CreateCell(16).SetCellValue(item.Fsliheattreatment);
                        row.CreateCell(17).SetCellValue(item.Fsliexplanation);
                        row.CreateCell(18).SetCellValue(item.FsliTestBarQty.GetValueOrDefault());
                        row.CreateCell(19).SetCellValue(item.Fnote);
                    }

                    // 自动调整列宽
                    for (int i = 0; i < headers.Length; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }

                    // 生成文件流
                    var stream = new MemoryStream();
                    workbook.Write(stream);

                    // 创建响应
                    var result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(stream.ToArray())
                    };
                    result.Content.Headers.ContentDisposition =
                        new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = $"WorkNotice_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                        };
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                    return result;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                    $"导出失败：{ex.Message}");
            }
        }
    }
}